import { get, post } from '@/utils/request'

// 智慧识鱼相关API接口
export const fishRecognitionApi = {
  // 获取最新识别记录（左上轮播）
  getRecentRecords: () => {
    return get('/records/recent')
  },

  // 获取使用统计（左下统计面板）
  getStatistics: () => {
    // 注意：这是WebSocket接口，需要单独处理
    return get('/statistics')
  },

  // 获取最热搜索排行（右上热榜）
  getHotRanking: () => {
    return get('/fish/hot-ranking')
  },

  // 获取鱼类画像（右下轮播）
  getFishProfiles: () => {
    return get('/gateway/fish/profiles')
  },
  
  // 算法调用-----------------------------
  // 搜索鱼类信息（通过文字搜索）
  searchFish: (params) => {
    return get('/gateway/fish/uploadSuggestion', params)
  },
  
  // 上传图片（通过图片搜索）
  uploadImage: (formData) => {
    return post('/gateway/fish/upload', formData)
  }
}
  // 算法调用=============================

// 获取操作日志
export const logget = {
  detail: " ",
  id: 1,
  img: " ",
  openid: " ",
  operation: " ",
  time: 1692880631000,
  username: ""
}

// 搜索鱼类信息
export const getfish = {
  id: 1,
  fishName: " ",
  scientificName: " ",
  description: " ",
  habitat: " ",
  characteristic: " ",
  images: " ",
  video: " "
}

// 最新识别记录响应类型
export const recentRecordResponse = {
  username: '', // 用户A
  uploadTime: '', // 2023-08-15 14:30:22
  fishName: '', // 大黄鱼
  confidence: 0, // 0.957
  thumbnail: '' // /images/thumbnail_001.jpg
}

// 使用统计响应类型
export const statisticsResponse = {
  onlineUsers: 0, // 在线用户数
  todayRecognitions: 0, // 今日识别次数
  totalRecognitions: 0, // 总识别次数
  totalImages: 0 // 总图片数
}

// 热榜响应类型
export const hotRankingResponse = {
  fishName: '', // 大黄鱼
  searchCount: 0, // 2345
  popularity: 0 // 11234
}

// 鱼类画像响应类型
export const fishProfileResponse = {
  fishName: '', // 大黄鱼
  scientificName: '', // Larimichthys crocea
  description: '', // 石首鱼科黄鱼属鱼类，体延长...
  habitat: '', // 西北太平洋区，中国沿海均有分布
  characteristic: '', // 体侧上半部为黄褐色...
  images: [], // ["/images/fish/001-main.jpg", "/images/fish/001-detail.jpg"]
  video: '' // /videos/fish/001.mp4
}
export class WebSocketClient {
  constructor(url) {
    this.url = url
    this.ws = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 3000
    this.onMessage = null
  }

  connect() {
    try {
      this.ws = new WebSocket(this.url)

      this.ws.onopen = () => {
        console.log('WebSocket连接成功')
        this.reconnectAttempts = 0
        // 主动请求一次统计数据
        this.send('getStats')
      }

      this.ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data)
          console.log('收到WebSocket消息:', data)
          if (this.onMessage) {
            this.onMessage(data)
          }
        } catch (error) {
          console.error('解析WebSocket消息失败:', error)
        }
      }

      this.ws.onclose = () => {
        console.log('WebSocket连接关闭')
        this.reconnect()
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket连接错误:', error)
      }
    } catch (error) {
      console.error('创建WebSocket连接失败:', error)
    }
  }

  reconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++
      console.log(`尝试重新连接WebSocket (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
      setTimeout(() => {
        this.connect()
      }, this.reconnectInterval)
    } else {
      console.error('WebSocket重连失败，已达到最大重连次数')
    }
  }

  disconnect() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
      //手动断开不允许重连
      this.reconnectAttempts = this.maxReconnectAttempts // 设置为最大重连次数，阻止自动重连
    }
  }

  send(data) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(typeof data === 'object' ? JSON.stringify(data) : data)
    } else {
      console.error('WebSocket未连接，无法发送消息')
    }
  }
}
// 创建WebSocket客户端实例
export const statisticsWebSocket = new WebSocketClient('wss://4b527230k9.zicp.fun/ws/statistics')